/**
 * Created by pkd 2019/4/8.
 */
var DBFactory = require('../db/mysql_db');
var userOnlineDao = module.exports;

var MaxSingleOnlineTime = 86400000;     // 每条记录最长的登陆时间是多少。为了优化查询语句而设。
var OnlineTimeUnit = 15000;             // 最短在线时长统计单位。
var OfflineTimeLen = 60000;             // 超过多长算掉线。
var SearchHeadTimeLen = 600000;         // 首次请求，从数据库找多长时间之前登陆的记录来匹配。

//添加在线记录
function SaveOnlineInfo(data, cb) {
    var sql = "Replace into `user_online`(`app_sid`, `uid`, `sub_uid`, `created_time`, `end_time`)values(?, ?,?,?,?)";
    var value = [data.app_sid, data.uid, data.sub_uid, data.created_time, data.end_time];
    DBFactory.poolQuery(sql, value,
        function () {
            cb('no collection');
        },
        function(error, result) {
            if (error) {
                cb(error);
                return;
            }
            result.created_time = data.created_time;
            result.end_time = data.end_time;
            result.app_sid = data.app_sid;
            cb(null, result);
        });
}

//添加在线记录
userOnlineDao.updateOnline = function(data, cb) {
    if(!data || !data.uid || !data.app_sid) {
        cb(new Error(500));
        return;
    }
    if(!data.sub_uid){data.sub_uid = data.uid;}

    if(!data.created_time || isNaN(data.created_time.getTime()) || !data.lastTime || isNaN(data.lastTime.getTime())){
        userOnlineDao.getRecentOnLineInfo({app_sid:data.app_sid, uid:data.uid, sub_uid:data.sub_uid}, function (err, result) {
            if (!err && result.length > 0) {
                data.created_time = result[0].created_time;
                data.lastTime = result[0].end_time;
                if(data.end_time.getTime() <= data.lastTime.getTime() + OnlineTimeUnit){
                    data.end_time = data.lastTime;
                    cb(null, data);
                    return;
                }
            }
            if(!data.created_time || isNaN(data.created_time.getTime())){
                data.created_time = new Date();
                data.lastTime = data.created_time;
            }
            userOnlineDao.updateOnline(data, cb);
        });
        return;
    }

    if(data.end_time.getTime() > data.lastTime.getTime() + OfflineTimeLen){
        data.created_time = new Date();
        data.end_time = new Date(data.created_time.getTime() + OnlineTimeUnit);
    }

    if(data.end_time.getTime() < data.created_time.getTime() + MaxSingleOnlineTime){
        SaveOnlineInfo(data, cb);
        return;
    }

    var endTime = data.end_time;
    data.end_time = new Date(data.created_time.getTime() + MaxSingleOnlineTime);
    SaveOnlineInfo(data, function (err, result) {
        if(err){
            cb(err);
            return;
        }
        data.created_time = data.end_time;
        data.end_time = endTime;
        SaveOnlineInfo(data, cb);
    });
};

//查询
userOnlineDao.getRecentOnLineInfo = function(data, cb) {
    if(!data || !data.uid || !data.app_sid) {
        cb(new Error(500));
        return;
    }
    var startTime = new Date(new Date().getTime() - SearchHeadTimeLen);

    var value = [data.app_sid, data.uid, startTime, data.sub_uid];
    var sql = 'select created_time, end_time from `user_online` ' +
        'where app_sid = ? AND uid = ? AND created_time >= ? AND sub_uid = ? order by created_time DESC limit 1';

    DBFactory.poolQuery(sql, value,
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            cb(null, result);
        }
    );
}

//查询
userOnlineDao.getOnLineInfo = function(data, cb) {
    if(!data || !data.uid) {
        cb(new Error(500));
        return;
    }
    var now = new Date();
    var startTime = data.created_time ? data.created_time : new Date(now.getFullYear(), now.getMonth(), now.getDate(), 24);
    var minStartTime = new Date(startTime.getTime() - MaxSingleOnlineTime);

    var value = [data.uid, minStartTime, startTime];
    var sql = 'select uid, sub_uid, count(created_time) as logCount, SUM(end_time - created_time) as timeLength from `user_online` ' +
        'where uid = ? AND created_time >= ? AND created_time <= ? ';

    if(data.app_sid){
        sql += ' AND app_sid = ? ';
        value.push(data.app_sid);
    }
    if(data.end_time){
        sql += ' AND end_time > ? ';
        value.push(data.end_time);
    }
    if(data.sub_uid){
        sql += ' AND sub_uid = ? ';
        value.push(data.sub_uid);
    }
    sql += ' group by app_sid, uid, sub_uid;';

    DBFactory.poolQuery(sql, value,
        function () {
            cb('no collection');
        },
        function (err, result) {
            if (err) {
                console.log(err);
                cb(err);
                return;
            }
            cb(null,result);
        }
    );
}